package com.ebay.util;  


import java.util.ArrayList;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.StrutsStatics;  

import com.ebay.model.UserModel;
import com.opensymphony.xwork2.ActionContext;  
import com.opensymphony.xwork2.ActionInvocation;  
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;  

@SuppressWarnings("serial")
public class SessionInterceptor extends AbstractInterceptor implements  
StrutsStatics {  

	public void init() {  

	}  

	public void destroy() {  
	}  

	public String intercept(ActionInvocation invocation) throws Exception {  

		final ActionContext context = invocation.getInvocationContext();  
		HttpServletRequest request = (HttpServletRequest) context  
		.get(HTTP_REQUEST);  

		
		Map<String,Object> session = context.getSession();
		ArrayList<String> restrictedContextNames = new ArrayList<String>();
		
		//TODO:add restricted context names here:
		restrictedContextNames.add("buyNow");
		restrictedContextNames.add("showCart");
		restrictedContextNames.add("showpaisapaydetails");
		restrictedContextNames.add("reviewBid");
		restrictedContextNames.add("confirmBid");
		
		
		String contextName = context.getName();
		String queryParam = request.getQueryString();
		
		if(contextName.equals("SignIn")){
			return invocation.invoke();
		}
		
		
		String url = contextName;
		String prevPrevUrl = (String) session.get("prevUrl");
		
		if(queryParam!=null)
			url += "?"+queryParam;
		session.put("prevUrl", url);
		if(!url.equals(prevPrevUrl))
			session.put("prevPrevUrl", prevPrevUrl);
		if(contextName.equals("displayItemList"))
			session.put("prevSearch", url);
		System.out.println("Interceptor : "+url);
		//check these actions : has to be logged in :
		
		UserModel user = (UserModel) session.get("user");
		if(restrictedContextNames.contains(contextName)&&user==null){//user not logged in!
			return "login";
		}
		
		return invocation.invoke();
		
		// Is there a "user" object stored in the user's HttpSession?  
		
	}  
}